<template>
    <div class="app-container">
        <levelbar></levelbar>
        <el-form label-width="120px" v-loading="loading" class="app-content" :rules="rules" :model="ruleForm" ref="ruleForm">
            <div class="box">
                <div class="appTitle">设置</div>
                <progressBar :active="temp"></progressBar>
                <div class="appTop" v-if="temp==1">设置考场</div>
                <div class="appTop" v-if="temp==2">创建考试科目（考试时间范围：{{timeRange[0].substring(0,timeRange[0].length-9)+' ~ '+timeRange[1].substring(0,timeRange[1].length-9)}}）</div>
                <div class="appTop" v-if="temp==3">设置考试注意事项（100字以内，可不填写） </div>
                <div class="table-title" slot="table-title" v-if="temp==1">
                    <div class="btnPosition">
                        <el-button @click="batchCreateExam">批量创建考场</el-button>
                    </div>
                </div>
                <div class="appCon" v-if="temp==1">
                    <!--                     
                        提示: 选择考场号和班级名称时：
                        1：逻辑修改：允许同一个教室（班级）最多对应2个考场；
                                    教室（班级）的使用次数超过2次，则提示：一个班级最多容纳两个考场；
                        -->
                    <div class="dataItem" v-for='(site,index) in ruleForm.dataNumber' :key="index">
                        <button v-if = "index == ruleForm.dataNumber.length - 1 && index" @click = "removeDomain(index)" type="button" aria-label="Close" class="el-dialog__headerbtn"><i class="el-dialog__close el-icon el-icon-close"></i></button>
                        <el-row>
                            <el-col :span='18' class='isUpdataPb'>
                                <el-form-item label="考场号：" :prop="'dataNumber.' + index + '.examNoText'" :rules="[{required: true, message: '考场号不能为空', trigger: 'blur'}, { pattern: /^[^\s]+$/, message: '请勿输入空格', trigger: 'blur, change' }]">
                                    <el-input v-model="site.examNoText" placeholder="请输入考场号" :maxlength="8"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span='18' class='isUpdataPb'>
                                <el-form-item label="班级名称：" :prop="'dataNumber.' + index + '.pId'" :rules="{required: true, message: '请选择班级名称', trigger: 'change'}">
                                    <cascadeClass 
                                    @change="classChange(site, index)" 
                                    :disabledOptions="site.disabledPid" 
                                    :emptyOption="false" v-model="site.pId" ></cascadeClass>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div v-if="temp==2">
                    <create-sub ref='createSub' :ExamInfo = "ruleForm.dataNumber" 
                    @submitData='getSubmitData' 
                    @lodingHideShow='lodingHideShow'>
                    </create-sub> 
                </div>
                <div class="textarea-box" v-if="temp==3">
                    <el-form-item label="" label-width="20px">
                        <el-input type="text" v-model="ruleForm.attentionDesc" :maxlength="100" placeholder="请输入考试注意事项"></el-input>
                    </el-form-item>
                </div>
            </div>
            <el-row v-if="temp==1">
                <el-button type="text" @click="addNumber" class="addBtn"><i class="el-icon-plus"></i> 继续添加</el-button>
            </el-row>
            <div class="footer" v-if='temp==1'>
                <el-button @click='back'>返回考场列表</el-button>
                <el-button type="primary" @click="nextStep('ruleForm')" v-if="temp<2">下一步</el-button>
            </div>
             <!--                     
                提示:temp==2
                1：原“提交”按钮改成“下一步”；
                    点击“下一步”验证是否有同一考场包含重叠时段的考试，且考试开始时间一致，如果开始时间不一致，
                    提示：【考场名称】的两场考试时间有重叠，开始时间必须一致；
            -->
            <div class="footer" v-if='temp==2'>
                <el-button @click='back'>返回考场列表</el-button>
                <el-button @click='lastStep'>上一步</el-button>
                <el-button type="primary" @click='getData'>下一步</el-button>
            </div>
            <div class="footer" v-if='temp==3'>
                <el-button @click='back'>返回考场列表</el-button>
                <el-button @click='lastStep'>上一步</el-button>
                <el-button type="primary" @click='submitBtn'>提交</el-button>
            </div>
        </el-form>
        <!-- 批量创建考场的弹窗： -->
        <batchCreateExamination @addExamState="addExamState" v-if="batchCreateExamination.dialogFormVisible" 
        :batchCreateExamination="batchCreateExamination"></batchCreateExamination>
    </div>
</template>
<script>
import Levelbar from '../layout/Levelbar';
import cascadeClass from './comps/cascadeClass';
import { listWisdomroom, updateWisdomExamroom, updateWisdomExamsubject, updateWisdomAttention, listWisdomAttention} from 'api/wisdom';
import { listClassBySchoolId } from 'api/common';
import batchCreateExamination from './comps/batchCreateExamination';
import getClass from 'components/SchoolClasss/class';
import createSub from './comps/createSub';
import progressBar from './comps/progressBar';
import { mapGetters } from 'vuex';
export default{
    name: 'examinationEdit',
    components: {Levelbar, batchCreateExamination, getClass, createSub, cascadeClass, progressBar},
    data() {
        return { 
            loading: true,
            ruleForm: {
                attentionDesc: '', // 考试注意事项内容
                dataNumber: [// 所有考场的信息
                    {
                        id: '',
                        fExamId: '',
                        examNoText: '第1考场',
                        pId: '', // 班级id
                        sNickName: '',
                        disabledPid: []// 禁用掉的班级id
                    }
                ]
            },
            batchCreateExamination: {
                dialogFormVisible: false,
                classMaxCount: 0// 还可以添加几个
            },
            timeRange: '', // 考试时间范围
            temp: 1, // 1 是添加考试完成 2是设置考场完成 3是创建考试科目完成 4是考试注意事项完成
            getTemp: 0, // 回填的考场数
            examTemp: 1, // 已经添加到页面的考场的总数
            examCount: 0, // 可设置的考场总数
            ChoosenpIds: [],
            subInfo: [],
            classList: [],
            examDate: [],
            rules: {}
        }
    },
    
    computed: {
        ...mapGetters([
            'schoolId',
            'schoolName'
        ])
    },
    created() {
        this.isUpdate().then(() => {
            this.getClass();
        });
    },
    methods: {
        // 数组里 重复两次的 拿出来
        repeat(arr) {
            var tmp = [];
            var newArr = [];
            // 使用set进行数组去重
            newArr = [...new Set(arr)];
            var newarr2 = new Array(newArr.length);
            for (var t = 0; t < newarr2.length; t++) {
                newarr2[t] = 0;
            }
            for (var p = 0; p < newArr.length; p++) {
                for (var j = 0; j < arr.length; j++) {
                    if (newArr[p] == arr[j]) {
                        newarr2[p]++;
                    }
                }
            }
            for (var m = 0; m < newArr.length; m++) {
                if (newarr2[m]==2) {
                    tmp.push(newArr[m])
                }
            }
            return tmp
            // var tmp = [];
            // arr.sort().sort(function(a, b) {
            //     // console.log(a==b,'111111')
            //     // console.log(a && b,'222222')
            //     // console.log(tmp.indexOf(a),'3333333333')
              
            //     if (a == b && a && b && tmp.indexOf(a) === -1) {
            //         console.log('8------------==============================')
            //         tmp.push(a)
            //     }
            // })
            // console.log(tmp,'tmp')
            // return tmp
            
        },
        lodingHideShow(status) {
            this.loading=status
        },
        // 是否更新
        isUpdate() {
            return listWisdomroom(this.$route.params.id).then(response => {
                this.loading=false;
                this.examDate[0] = response.data.content.sStartDate;
                this.examDate[1] = response.data.content.sEndDate;
                this.timeRange = [...this.examDate];
                if (response.data.content.listExamroom) {
                    this.ruleForm.dataNumber = [];
                    response.data.content.listExamroom.forEach(item => {
                        let classObj = {
                            fExamId: item.pId,
                            examNoText: item.sRoomnum,
                            pId: item.fClassId,
                            sNickName: item.sRoomnum,
                            disabledPid: []
                        };
                        this.ruleForm.dataNumber.push(classObj);
                    });
                    this.examTemp = 0;
                    this.getTemp = response.data.content.listExamroom.length;// 回填的考场数
                }
            });
        },
        // 获取班级
        getClass() {
            listClassBySchoolId(this.schoolId).then(res => {
                if (res.data.content.length) {
                    this.classList = res.data.content;
                    if (this.ruleForm.dataNumber[0]) {
                        this.ruleForm.dataNumber[0].classList = this.classList;
                    }
                    this.examCount = this.classList.length*2;// 可设置的考场总数
                    this.batchCreateExamination.classMaxCount = this.examCount - this.examTemp - this.getTemp;// 可设置的考场总数  ——— 已添加上的  —— 回填的
                }
            }).catch(() => {
                this.loading=false;
            });
        },
        // 查询修改班级 选择班级时 禁用掉 重复使用两次的班级
        classChange(row, index) {
            for (let i = 0; i < this.ruleForm.dataNumber.length; i++) {// 编辑所有考场
                let newArr = [];
                let newArr2=[];
                for (let j = 0; j < this.ruleForm.dataNumber.length; j++) {
                    if (i != j) {
                        newArr.push(this.ruleForm.dataNumber[j].pId);
                        newArr2=this.repeat(newArr);// Pid 选2次了 就push
                    }
                }
                this.ruleForm.dataNumber[i].disabledPid = newArr2;// 禁用使用过2次的班级
            }
        },

        // 点击批量创建考场 按钮
        batchCreateExam() {
            this.batchCreateExamination.dialogFormVisible = true;
        },
        // 批量添加classNum个考场，页面上展现出来
        addExamState(classNum) {
            this.examTemp = this.examTemp + parseInt(classNum);// 已添加上去的考场
            for (var i = 0; i < classNum; i++) {
                this.batchCreateExamination.classMaxCount = this.examCount - this.examTemp - this.getTemp;
                let NumberObj = {
                    examNoText: '第' + (this.ruleForm.dataNumber.length + 1) + '考场',
                    classList: this.classList,
                    pId: '',
                    sNickName: '',
                    disabledPid: []
                };
                NumberObj.disabledPid.length = this.ruleForm.dataNumber.length;
                this.ruleForm.dataNumber.forEach((item, index) => {
                    if (item.pId) {
                        NumberObj.disabledPid.splice(index, 1, item.pId);
                    } 
                });
                this.ruleForm.dataNumber.push(NumberObj);
            }
            this.classChange();
        },
        // 获取要给后台的数据
          // 获取要给后台的数据
        getSubmitData(info, backInfo) {
            // console.log(info, '----info---')
            // console.log(backInfo, '----backInfo---')
            this.subInfo=[];
            for (let i = 0; i< info.length; i++) {
                for (let j = 0; j< info[i].ExamNoIds.length; j++) {
                    let pId='';// 只给回填过来的给pId赋值
                    backInfo.forEach((back, backIndex) => {
                        if (backIndex==i) {
                            back.sRoomnum.forEach((id, index) => {
                                if (id==info[i].ExamNoIds[j].pId) {
                                    pId=back.pIds[index]
                                }
                            })
                        }
                    })
                    this.subInfo.push({
                        pId, // 新增的是""  回填的要传pId"
                        sMasterTeacher: info[i].sMasterTeacher, // 监考老师
                        fExamroomId: info[i].ExamNoIds[j].pId, // 考场id
                        fSubjectid: info[i].examSub, // 考试科目id  
                        sStarttime: info[i].examDate[0], // 开始时间
                        sEndtime: info[i].examDate[1]// 结束时间
                    });
                    // console.log(this.subInfo,'this.subInfo给他的---')
                }
            }
            this.createSubject();
        },
        // 提交按钮
        submitBtn() {
            this.$confirm('确定要提交吗？', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.loading = true;
                updateWisdomAttention(this.$route.params.id, this.ruleForm.attentionDesc).then(response => {
                    this.temp++;// 第三步完成 到第四步
                    this.loading = false;
                    this.$message({
                        type: 'success',
                        message: '设置成功'
                    });     
                    this.$router.push({path: '/examinationMode/examinationMode'});    
                    // 刷新列表
                    this.$store.dispatch('UpdateCache', true); // 列表刷新

                }).catch(() => {
                    this.loading = false;
                });
            });
           
        },
        // 创建科目
        createSubject() {
            this.loading=true;
            updateWisdomExamsubject(this.$route.params.id, this.subInfo).then(response => {
                this.loading = false;
                this.temp=3;  
                // 回填考试注意事项
                let json={
                    pId: this.$route.params.id
                }
                listWisdomAttention(json).then(res => {
                    this.ruleForm.attentionDesc=res.data.content;
                })
            }).catch(() => {
                this.loading = false;
            });
        },
        // 批量添加后的删除
        removeDomain(index) {
            this.$confirm('确定要删除考场?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.examTemp--;
                this.batchCreateExamination.classMaxCount = this.examCount - this.examTemp - this.getTemp;
                this.releaseClass(index);
                this.ruleForm.dataNumber.splice(index, 1);
                this.classChange()
            });
        },
        releaseClass(index) {
            let newArr = []; 
            for (let i = 0; i < this.ruleForm.dataNumber.length; i++) {
                newArr = this.ruleForm.dataNumber[i].disabledPid.filter(item => {
                    return item != this.ruleForm.dataNumber[index].pId;
                });
                this.ruleForm.dataNumber[i].disabledPid = newArr;
            }
        },
        // 继续单个添加
        addNumber() {
            if (this.ruleForm.dataNumber.length >= this.examCount) {
                this.$message({
                    type: 'warning',
                    message: '最多可添加' + this.examCount + '个考场'
                });
                return '';
            }
            this.examTemp ++;
            this.batchCreateExamination.classMaxCount = this.examCount - this.examTemp - this.getTemp;
            let NumberObj = {
                id: '',
                fExamId: '',
                examNoText: '第' + (this.ruleForm.dataNumber.length + 1) + '考场',
                classList: this.classList,
                pId: '',
                sNickName: '',
                disabledPid: []
            };
            NumberObj.disabledPid.length = this.ruleForm.dataNumber.length;
            this.ruleForm.dataNumber.forEach((item, index) => {
                if (item.pId) {
                    NumberObj.disabledPid.splice(index, 1, item.pId);
                } 
            });
            this.ruleForm.dataNumber.push(NumberObj);
            this.classChange();
        },
        lastStep() {
            this.temp--;
            if (this.temp!==1) {
                this.loading=true;
            }
        },
        // 第一个下一步
        nextStep(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    let nameArr = [];
                    this.ruleForm.dataNumber.forEach(item => {
                        nameArr.push(item.examNoText);
                    });
                    let items = new Set(nameArr);
                    if (items.size != nameArr.length) {
                        this.$message({
                            type: 'info',
                            message: '考场号不能重复'
                        });
                        return;
                    }
                    this.loading = true;
                    let listExamroom = [];
                    this.ruleForm.dataNumber.forEach(item => {
                        listExamroom.push({
                            pId: item.fExamId,
                            sRoomnum: item.examNoText,
                            fClassId: item.pId
                        })
                    });
                    if (listExamroom) {
                        updateWisdomExamroom(this.$route.params.id, listExamroom).then(response => {
                            this.temp++;   
                            this.loading = true;
                        }).catch(() => {
                            this.loading = false;
                        });
                    } else {
                        return false;
                    }
                }
            });
        },
        back() {
            this.$router.push({ path: '/examinationMode/examinationMode'});
            this.$store.dispatch('UpdateCache', true); // 列表刷新
        },
        getData() { // 下一步 获取给后台的数据 跳到提交按钮的页面
            this.$refs.createSub.submitForm();
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    .textarea-box{
        .el-textarea__inner{
            height: 150px !important;
        }
        margin-bottom: 60px;
    }
    .app-levelbar {
        height: 35px;
    }
    .el-form{
        box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        background:#fff;
        padding-bottom:100px;
        .appCon{
            margin-top:50px;
            overflow: hidden;
            .dataItem{
                position: relative;
                float: left;
                width: 47%;
                height: 185px;
                margin-bottom:40px;
                padding-top: 35px;
                border:#ccc 1px solid;
                .el-dialog__headerbtn{
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }
                .close{
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }
            }
            .dataItem:nth-of-type(2n){
                margin-left:6%
            }
        }
        .appTop{
            position: relative;
            font-size: 14px;
            color: rgb(106, 85, 72);
            padding-left: 16px;
            margin: 30px 0;
            display: block;
            &::after {
                position: absolute;
                content:'';
                width: 4px;
                height: 14px;
                background: #ff5e2c;
                left: 0;
                top: 3px;
            }
        }
        .appTitle{
            padding-top:8px;
            text-align: center;
            font-size: 18px;
            color: #333;
            line-height: 72px;
            font-weight: bold;
            font-family: Microsoft YaHei;
            border-bottom: 1px solid #ddd;
        }
        .box{
            padding: 0px 50px;
            background:#fff;
        }
       .footer{
            text-align:center
        }
        .addBtn{
            margin:0px 0 50px 50px;
            font-size: 14px;
            color: #ff5e2c;
        }
        .delBtn {
            font-size: 20px;
            color:#999;
            margin-left:30px;
        }
        .imageBox{
            height:330px;
            margin-left:30px;
        }
        .isUpdataPb{
            margin-bottom:15px;
        }
    }
    
}

</style>
